package threadcoreknowledge.stopthreads.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 生产者生产快速，消费者速度慢
 * 所以队列满了之后，生产者会阻塞，等待消费者消费
 */
public class WrongWayVolatileCantStop {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<Integer> storage = new ArrayBlockingQueue<Integer>(10);
        Producer producer = new Producer(storage);
        Thread producerThread = new Thread(producer);
        producerThread.start();

        Consumer consumer = new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.getStorage().take() + "已经被消费");
            Thread.sleep(1000);
        }
        System.out.println("消费者不需要更多数据了");
        // 停止生产数据
        producer.canceled = true;
    }
}

class Producer implements Runnable {
    private BlockingQueue<Integer> storage;
    public volatile boolean canceled = false;

    public Producer(BlockingQueue<Integer> storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        int num = 0;
        try {
            while (num <= 10000 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍数，被放到仓库了");
                    storage.put(num);
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者停止运行");
        }
    }
}

class Consumer {
    private BlockingQueue storage;

    public Consumer(BlockingQueue storage) {
        this.storage = storage;
    }

    public boolean needMoreNums() {
        System.out.println(Math.random());
        return !(Math.random() > 0.95);
    }

    public BlockingQueue getStorage() {
        return storage;
    }
}